#include "luafile.h"
#include <qstringlist.h>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include "../lua_parser/Token.h"

LuaFile::LuaFile(QString aPath)
{
    m_path = aPath;
    m_isSaved = false;
    m_scrollOffset = 0;
}


LuaFile::~LuaFile()
{

}

QString LuaFile::getPath()
{
    return m_path;
}

void LuaFile::setContent(QString aContent)
{
    if(m_content == aContent)
        return;
    m_content = aContent;
    m_isSaved = false;
    save();
    this->parseData(m_content);
    //refreshGlobals(aSink);
}

void LuaFile::reloadFromFileSystem(GlobalSink * aSink)
{
    QStringList fileData;
    QFile file(m_path);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    while (!in.atEnd())
    {
        QString line = in.readLine();
        fileData.append(line);
    }
    setContent(fileData.join("\n"));
    m_isSaved = true;
}

TokenParser * LuaFile::getTokenParser()
{
    return m_tokenParser;
}


QString LuaFile::getText()
{
    return m_content;
}

void LuaFile::addMatchingLocals(int aOffset, QString aMatch, QStringList &aList)
{
    //m_parser->addMatchingLocals(aOffset, aMatch, aList);
}

void LuaFile::save()
{
    QFile file(m_path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox messageBox;
        messageBox.critical(0,"Error","Unable to save file " + m_path + "!");
        return;
    }

    QTextStream out(&file);
    out << m_content;
    file.close();
    m_isSaved = true;
}

bool LuaFile::isSaved()
{
    return m_isSaved;
}



bool LuaFile::hasGlobal(const QString &aText)
{
    //return m_parser->hasGlobal(aText);
    return false;
}


void LuaFile::addMatchingGlobals(QString aMatch, QStringList &aList)
{
    //m_parser->addMatchingGlobals(aMatch, aList);
}


bool LuaFile::getParameterForToken(LuaToken *aToken, LuaToken **aParameter)
{
    //return m_parser->getParameterForToken(aToken, aParameter);
    return false;
}


bool LuaFile::hasGlobalMethod(const QString aText)
{
    //return m_parser->hasGlobalMethod(aText);
    return false;
}


int LuaFile::getScrollOffset()
{
    return m_scrollOffset;
}

void LuaFile::setScrollOffset(int aOffset)
{
    m_scrollOffset = aOffset;
}


void LuaFile::getAllGlobalFunctions(QStringList &aSink)
{
    //m_parser->getAllGlobalFunctions(aSink);
    QStringList keys = m_globalFunctionsCache.keys();
    for(int i =0; i < keys.size(); i++)
        aSink.append(keys[i]);
}

void LuaFile::getAllLocalFunctions(QStringList &aSink)
{
    //m_parser->getAllLocalFunctions(aSink);
    QStringList keys = m_localFunctionsCache.keys();
    for(int i =0; i < keys.size(); i++)
        aSink.append(keys[i]);
}

int LuaFile::getOffsetByFunctionHeader(QString aHeader)
{    
    if(m_globalFunctionsCache.contains(aHeader))
        return m_globalFunctionsCache[aHeader];
    if(m_localFunctionsCache.contains(aHeader))
        return m_localFunctionsCache[aHeader];
    return 0;
}

